<script lang="ts" setup>
import type { ReworkDocInput } from '#/api/rework/reworkDoc';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { updateOnlineReworkDocApi } from '#/api/rework/reworkDoc';

import { useSchema } from '../data';

const emit = defineEmits<{
  success: [];
}>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: useSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = (await formApi.getValues()) as ReworkDocInput;
      try {
        await updateOnlineReworkDocApi(data);
        modalApi.close();
        emit('success');
      } finally {
        modalApi.unlock();
      }
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<Record<string, any>>();
      const { lineId, defects } = data;
      const defectIds = defects?.map((defect: any) => defect.defectId);
      await formApi.setValues(Object.assign({}, data, { defectIds }), false);

      formApi.updateSchema([
        {
          componentProps: {
            params: { lineId },
            immediate: true,
          },
          fieldName: 'targetOperationId',
        },
      ]);
    }
  },
  title: '在线返工编辑',
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
